<template>
  <div class="app-container">
    <el-row
      style="display: flex; justify-content: space-between; margin-top: 0.5rem"
    >
      <span class="title">文章标题</span>
      <el-input
        ref="title_input"
        class="title_input"
        v-model="form.title"
        placeholder="请输入文章标题 （5-30）个字"
        maxlength="30"
      >
      </el-input>
      <el-button
        class="title_button draft_button"
        round
        @click="handleSave"
        v-if="!aId"
        >保存草稿</el-button
      >
      <el-button class="title_button save_button" round @click="open = true"
        >发布文章</el-button
      >
    </el-row>
    <el-row class="markdown_edit_content">
      <mavon-editor
        ref="md"
        v-model="form.content"
        @imgAdd="addImg"
        style="min-height: 800px"
      />
    </el-row>
    <el-dialog
      class="write_dialog"
      :title="title"
      :visible.sync="open"
      width="50%"
      :before-close="handleClose"
      append-to-body
    >
      <el-form id="form" ref="form" :model="form" label-width="90px">
        <el-row :gutter="20">
          <el-col  :offset="2" :span="20">
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :offset="2" :span="10">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
                <!-- <el-option :key="'1'" label="女" :value="'1'" /> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col  :span="10">
            <el-form-item label="标签" prop-="tags">
              <el-select v-model="form.tags" placeholder="请选择" multiple>
                <el-option
                  v-for="tag in tagList"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> </el-row>
        <el-row :gutter="20">
          <el-col :offset="2"  :span="20">
            <el-form-item label="文章摘要" prop="summary">
              <el-input v-model="form.summary" type="textarea"  :autosize="{ minRows: 2, maxRows: 4}" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :offset="2" :span="10">
            <el-form-item label="允许评论" prop="isComment">
              <el-radio-group v-model="form.isComment">
                <el-radio :key="'0'" :label="'0'">正常</el-radio>
                <el-radio :key="'1'" :label="'1'">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col  :span="10">
            <el-form-item label="是否置顶" prop="isTop">
              <el-radio-group v-model="form.isTop">
                <el-radio :key="'1'" :label="'1'">是</el-radio>
                <el-radio :key="'0'" :label="'0'">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" />

        <el-row :gutter="20">
          <el-col :offset="2" :span="20">
            <el-form-item label="缩略图">
              <el-upload style="width: 60%;"
                :file-list="fileList"
                class="upload-demo"
                list-type="picture"
                drag
                name="img"
                action="upload"
                :on-remove="fileRemove"
                :limit="1"
                :http-request="handleUpload"
                :on-exceed="onExceed"
                width:
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="6">
            <el-form-item>
              <!-- <el-button type="primary" size="medium" @click="handleSubmit">{{
                aId ? "更新" : "发布"
              }}</el-button> -->
              <el-button type="primary" size="medium" @click="handleSubmit"
                >确认</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :offset="3" :span="6">
            <el-form-item>
              <el-button type="info" @click="cancel">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listAllCategory } from "@/api/content/category";
import { uploadImg } from "@/api/content/upload";
import { addArticle, getArticle, updateArticle } from "@/api/content/article";
import { listAllTag } from "@/api/content/tag";
export default {
  name: "Write",
  data() {
    return {
      title: "", // 弹窗标题
      open: false, // 弹框开关
      form: {
        title: "",
        thumbnail: "",
        isTop: "1",
        isComment: "0",
        content: "",
      },
      categoryList: [],
      tagList: [],
      aId: -1,
      fileList: [],
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.aId = route.query && route.query.id;
        console.log(this.aId);
      },
      immediate: true,
    },
  },
  created() {
    this.getCategoryAndTag();
    if (this.aId) {
      this.getArticle();
    }
  },
  methods: {
    // 弹框关闭方法
    handleClose(){
      this.open = false;
    },
    // 弹框取消按钮
    cancel() {
      this.handleClose();
    },
    getArticle() {
      getArticle(this.aId).then((response) => {
        this.form = response;
        this.fileList.push({ name: "缩略图", url: response.thumbnail });
      });
    },
    handleSave() {
      this.form.status = "1";
      addArticle(this.form).then((response) => {
        this.$modal.msgSuccess("保存草稿成功");
      });
    },
    handleSubmit() {
      if (!this.aId) {
        this.form.status = "0";
        addArticle(this.form).then((response) => {
          this.$modal.msgSuccess("博客发布成功");
          this.$router.push({ path: "/content/article" });
        });
      } else {
        // 更新博客信息
        this.form.status = "0";
        updateArticle(this.form).then((response) => {
          this.$modal.msgSuccess("博客更新成功");
          this.$router.push({ path: "/content/article" });
        });
      }
    },
    onExceed() {
      this.$message.error("只能上传一个图片");
    },
    handleUpload(img) {
      uploadImg(img.file)
        .then((response) => {
          this.form.thumbnail = response;
          this.fileList.push({ name: img.file.name, url: response });
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    fileRemove(file, fileList) {
      this.fileList.pop();
    },
    // 绑定@imgAdd event
    addImg(pos, file) {
      // 第一步.将图片上传到服务器.
      uploadImg(file)
        .then((response) => {
          this.$refs.md.$img2Url(pos, response);
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    getCategoryAndTag() {
      listAllCategory().then((response) => {
        this.categoryList = response;
      });
      listAllTag().then((response) => {
        this.tagList = response;
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style scoped lang="scss">
$button-color: #fc5531;
$text-color: #fff;
$draft-hover-color: #fff5f2;
$save-hover-color: #fc1944;
.app-container {
  .title {
    color: rgb(87, 78, 78);
    font-size: 20px;
    line-height: 2.5rem;
  }

  .title_input {
    width: 70%;
    height: 30px;
    min-width: 40%;
    font-size: 24px;
   
    .el-input__inner {
      border: 1;
      border-radius: 95px;
      box-shadow: 0 0 0 0px;
      font-weight: 700;
    }
  }

  .title_button {
    color: #ffff;
    background-color: $button-color;
    width: 10%;
    font-size: 16px;
    &:hover {
      background-color: $save-hover-color;
    }
  }
  .draft_button {
    background-color: $text-color;
    color: $button-color;
    &:hover {
      background-color: $draft-hover-color;
    }
  }

  .markdown_edit_content {
    margin-top: 20px;
  }

 
}

div .upload-demo {
  /* padding-left: 80px; */
}

.el-col .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;

  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
